package ch.ffhs.services;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

/**
 * class SmsRecevier. Implements a broadcast-receiver for receiving
 * alarm-stop-sms-messages.
 * 
 * @author mf
 * @author td
 */
public class SmsReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.d("SmsReceiver", "onReceive");

		// Get the SMS map from Intent
		Bundle extras = intent.getExtras();

		String messages = "";

		Boolean stopAlarm = false;

		if (extras != null) {
			// Get received SMS array
			Object[] smsExtra = (Object[]) extras.get("pdus");

			for (int i = 0; i < smsExtra.length; ++i) {
				SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);

				String body = sms.getMessageBody().toString();
				String address = sms.getOriginatingAddress();

				if (body.contains("STOP ALARM")) {
					stopAlarm = true;
					break;
				}

				messages += "SMS from " + address + " :\n";
				messages += body + "\n";
			}

			// Display SMS message
			Toast.makeText(context, messages, Toast.LENGTH_SHORT).show();
		}

		if (stopAlarm) {
			// it's an alarm-sms, abort further broadcasts
			this.abortBroadcast();

			Log.d("SmsReceiver", "onReceive - stop alarm");

			// stop alarm
			if (ServiceManager.currentServiceManager != null) {
				ServiceManager.currentServiceManager.stopAlarmFromSms();
			}
		}
	}
}
